﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp12
{
    /// <summary>
    /// 指针帮助类
    /// </summary>
    public static class IntPtrHelper
    {
        /// <summary>
        /// 将指针转化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="intPtr"></param>
        /// <returns></returns>
        public static T ToModel<T>(this IntPtr intPtr)
        {
            return Marshal.PtrToStructure<T>(intPtr);
        }

        /// <summary>
        /// 将指针转化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static IntPtr ToIntPtr<T>(this T model)
        {
            IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(model));
            Marshal.StructureToPtr(model, intPtr, true);
            return intPtr;
        }
    }
}
